package com.xyy.service.impl;

import com.xyy.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    
    @Value("${spring.mail.username}")
    private String from;
    
    private final JavaMailSender mailSender;
    
    public EmailServiceImpl(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }
    
    @Override
    public boolean sendVerificationCode(String to, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("义诊活动预约系统 - 邮箱验证码");
            message.setText("您的验证码是：" + code + "，有效期5分钟，请勿泄露给他人。");
            
            mailSender.send(message);
            log.info("验证码邮件发送成功，收件人：{}", to);
            return true;
        } catch (Exception e) {
            log.error("发送验证码邮件失败，收件人：{}，错误：{}", to, e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean sendPasswordResetCode(String to, String code) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject("义诊活动预约系统 - 密码重置验证码");
            message.setText("您的密码重置验证码是：" + code + "，有效期5分钟，请勿泄露给他人。");
            
            mailSender.send(message);
            log.info("密码重置邮件发送成功，收件人：{}", to);
            return true;
        } catch (Exception e) {
            log.error("发送密码重置邮件失败，收件人：{}，错误：{}", to, e.getMessage());
            return false;
        }
    }
    
    @Override
    public boolean sendEmailCode(String email, String username) {
        try {
            // 生成6位随机验证码
            String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
            
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(email);
            message.setSubject("义诊活动预约系统 - 邮箱验证码");
            
            String content = "您的验证码是：" + code + "，有效期5分钟，请勿泄露给他人。";
            if (username != null && !username.trim().isEmpty()) {
                content = "尊敬的 " + username + "，\n\n" + content;
            }
            
            message.setText(content);
            
            mailSender.send(message);
            log.info("邮箱验证码发送成功，收件人：{}，验证码：{}", email, code);
            return true;
        } catch (Exception e) {
            log.error("发送邮箱验证码失败，收件人：{}，错误：{}", email, e.getMessage());
            return false;
        }
    }
} 